import { useLoadingBar, useMessage } from 'naive-ui';
import { saveAs } from 'file-saver';
import request from '@/utils/http';
import { toFormUrlEncoded } from '@/utils'; // 按你项目实际写
import { ref } from 'vue';

function isValidBlob(data: any) {
  return data instanceof Blob;
}

export function useDownload() {
  const loadingBar = useLoadingBar();
  const message = useMessage();
  const loading = ref(false);

  async function download(url: string, params: any, filename: string, config: any = {}) {
    try {
      loading.value = true;
      loadingBar.start();

      const res: any = await request.post(url, params, {
        transformRequest: [(params) => toFormUrlEncoded(params)],
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        responseType: 'blob',
        ...config,
      });

      // 可能返回错误 JSON
      if (!isValidBlob(res)) {
        const resText = await res.text();
        const obj = JSON.parse(resText);
        const errMsg = obj.msg || '下载失败';
        message.error(errMsg);
        loadingBar.error();
        return;
      }

      saveAs(new Blob([res]), filename);
      loadingBar.finish();
    } catch (err) {
      console.error(err);
      message.error('下载文件出现错误，请联系管理员！');
      loadingBar.error();
    } finally {
      loading.value = false;
    }
  }

  return { download, loading };
}
